﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Net_SCADA;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using NetSCADA_QUERY;
using System.Drawing.Printing;

namespace WZXC_GBL_QUERY
{
    public partial class Form_NewQueryDataByDay : Form
    {
        private int[] TimeSep = new int[16] { 5, 10, 15, 30, 45, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360 };
        private bool isLoadInterface = false;
        private Size ScreenSize;
        private Dictionary<int, CurveSetting> LineSetting = new Dictionary<int, CurveSetting>();
        private Label[] lbl_AxisLeft = new Label[6];
        private Label[] lbl_AxisRight = new Label[6];
        private Button selectedGroupButton = null;
        private int SelectPanelCols = 6;
        private int SelectPanelHeight = 42;
        Dictionary<CheckBox, List<CheckBox>> ZoneGroupChk = new Dictionary<CheckBox, List<CheckBox>>();
        Dictionary<CheckBox, List<Label>> ZoneGroupLbl = new Dictionary<CheckBox, List<Label>>();
        Ini inifile = new Ini(Application.StartupPath + @"\Settings\Curve.dat");
        private float xScale = 1;
        private bool isDateChanged = false;
        private Dictionary<int, yAxis[]> Y_Axis = new Dictionary<int, yAxis[]>();
        private int SelectedGroupID = 1;
        //显示详细数据使用
        private Label TimeLine = new Label() { Width = 1, BackColor = Color.Black};

        #region 打印机功能 变量
        PrintDocument print = new PrintDocument();
        string DefaultPrinterName = "";
        int totalpages = 0;
        int CurrentPageIndex = 0;
        float pageMargin = 30f;
        float MarginScale = 0.0336134f;
        SizeF pageSize = new SizeF(100, 100);
        SizeF _labelBlockSize = new SizeF(100, 100);
        PointF _labelLoaction = new PointF(100, 100);
        float Axisleft;
        float Axisright ;
        float Axistop;
        float AxisHeight;
        float AxisDivHeight;
        #endregion


        #region 多天查询变量定义
        public List<QueryOneDayData> DataOfDay = new List<QueryOneDayData>();
        private DateTime nextDate;
        private DateTime preDate;

        #endregion

        public Form_NewQueryDataByDay()
        {
            InitializeComponent();
        }

        #region 初始化界面
        private void Form_NewQueryDataByDay_Load(object sender, EventArgs e)
        {
            isLoadInterface = true;
            ScreenSize = Screen.PrimaryScreen.WorkingArea.Size;
            Show();
            SetInterface();
            LoadCurveSetting();
            LoadQueryButton();
            dtp_Day.Value = DateTime.Now.Date;
            isLoadInterface = false;
            nextDate = dtp_Day.Value;
            preDate = dtp_Day.Value.AddDays(-1);
            ShowNextDay();
            DefaultPrinterName = PubPrint.LoadPrinters(print,cmb_Printers);
            print.PrintPage += Print_PrintPage;
            print.QueryPageSettings += Print_QueryPageSettings;
        }

        private void Print_QueryPageSettings(object sender, QueryPageSettingsEventArgs e)
        {
            e.PageSettings.Landscape=true;//控制打印方向  true  横向
        }

        private void SetInterface()
        {
            gp_LoadData.Location = new Point((ScreenSize.Width - gp_LoadData.Width) / 2, (ScreenSize.Height - gp_LoadData.Height) / 3);
            cmb_FunctionSelect.Location = new Point(ScreenSize.Width - dtp_Day.Width - 5, 1);
            dtp_Day.Location = new Point(cmb_FunctionSelect.Left - dtp_Day.Width - 5, 1);
            dtp_Day.Value = DateTime.Now.Date;
            pnl_DayQuery.Location = new Point(0, 33);
            pnl_DayQuery.Size = new Size(ScreenSize.Width, ScreenSize.Height - 60);
            pnl_Curve.Location = new Point(0, 5);
            pnl_Curve.Size = new Size(ScreenSize.Width, pnl_DayQuery.Height - pnl_DayInfo.Height - pnl_Equip.Height - 5);
            pnl_Pics.Location = new Point(pic_AxisL.Width, 0);
            pnl_Pics.Size =new Size(ScreenSize.Width-pic_AxisL.Width -pic_AxisR.Width,  pnl_Curve.Height-hScroll.Height);
            TimeLine.Height = pnl_Pics.Height;
            pnl_Pics.Controls.Add(TimeLine);
            TimeLabel.Top = pnl_Pics.Height  - TimeLabel.Height-1;
            TimeData.Top = 2;
            lbl_LeftTitle.Parent = pic_AxisL;
            lbl_RightTitle.Parent = pic_AxisR;
            lbl_RightTitle.Location = new Point(30, 1);
            lbl_LeftTitle.Location = new Point(2, 1);
            cmb_FunctionSelect.Items.AddRange(new string[] { "请选择操作", "查看数据", "查看警报", "打印曲线" });
            cmb_FunctionSelect.SelectedIndex = 0;
            for (int i = 0; i < lbl_AxisLeft.Length; i++)
            {
                pic_AxisL.Controls.Add(lbl_AxisLeft[i] = new Label()
                {
                    Size = new Size(pic_AxisL.Width, 16),
                    TextAlign = ContentAlignment.TopRight
                });
                pic_AxisR.Controls.Add(lbl_AxisRight[i] = new Label()
                {
                    Size = new Size(pic_AxisR.Width, 16),
                    TextAlign = ContentAlignment.TopLeft
                });
            }
            SetYAxisLoaction();
            Pnl_LimitSet.Location = new Point((ScreenSize.Width - Pnl_LimitSet.Width) / 2, (ScreenSize.Height - Pnl_LimitSet.Height) / 2);
            pnl_PrintCurve.Location = new Point((ScreenSize.Width - pnl_PrintCurve.Width) / 2, (ScreenSize.Height - pnl_PrintCurve.Height) / 2);

            btn_NextDay.Left = ScreenSize.Width - btn_NextDay.Width - 60;
            btn_PreDay.Left = btn_NextDay.Left - btn_PreDay.Width - 5;
            btn_ZoomIn.Left = btn_PreDay.Left - btn_ZoomIn.Width - 20;
            lbl_xScaleValue.Left = btn_ZoomIn.Left - lbl_xScaleValue.Width;
            btn_ZoomOut.Left = lbl_xScaleValue.Left - btn_ZoomOut.Width;

        }
        private void LoadQueryButton()
        {
            string[] groupid = DBOperate.GetZoneMonitorGroupUsed();
            float v;
            if (groupid == null || groupid.Length <= 0) return;
            DataTable dtGroup = DBOperate.GetDesignGroupSet();
            if (dtGroup == null || dtGroup.Rows.Count <= 0) return;
            for (int i = groupid.Length - 1; i >= 0; i--)
            {
                int gid = Convert.ToInt32(groupid[i]);
                int cols = Convert.ToInt32(dtGroup.Select("groupid=" + groupid[i])[0]["QueryCols"].ToString());
                Y_Axis[gid] = new yAxis[2] { new yAxis(), new yAxis() };
                Y_Axis[gid][0].min = float.TryParse(inifile.ReadValue("EquipGroup" + groupid[i], "lmin"), out v) ? v : 0;
                Y_Axis[gid][0].max = float.TryParse(inifile.ReadValue("EquipGroup" + groupid[i], "lmax"), out v) ? v : 1000;
                Y_Axis[gid][0].unit = inifile.ReadValue("EquipGroup" + groupid[i], "lunit");
                Y_Axis[gid][1].min = float.TryParse(inifile.ReadValue("EquipGroup" + groupid[i], "rmin"), out v) ? v : 0;
                Y_Axis[gid][1].max = float.TryParse(inifile.ReadValue("EquipGroup" + groupid[i], "rmax"), out v) ? v : 1000;
                Y_Axis[gid][1].unit = inifile.ReadValue("EquipGroup" + groupid[i], "runit");
                Button btn = new Button()
                {
                    Size = new Size(120, 50),
                    Text = dtGroup.Select("groupid=" + groupid[i])[0]["groupname"].ToString(),
                    Font = new Font("宋体", 10.5f, FontStyle.Regular),
                    FlatStyle = FlatStyle.Flat,
                    Location = new Point(5 + i * 125, 1),
                    Tag = new int[2] { gid, cols }
                };
                btn.Click += Btn_Click;
                pnl_Equip.Controls.Add(btn);
                if (i == 0) selectedGroupButton = btn;
            }
            ShowZoneSelections(selectedGroupButton);
        } 
        private void LoadCurveSetting()
        {//显示天数据时的设置

            //for (int i = 0; i < QueryForms.fmquery.netline.zone.Count; i++)
            foreach (var z in QueryForms.fmquery.netline.zone.Values)
            {
                if (z.isShowCurve)
                {
                    if (z.pv != null)
                    {
                        LineSetting.Add(z.pv.ID, new CurveSetting(z.pv.ID));
                    }
                    if (z.sv != null)
                    {
                        LineSetting.Add(z.sv.ID, new CurveSetting(z.sv.ID));
                    }
                    if (z.ovpv != null)
                    {
                        LineSetting.Add(z.ovpv.ID, new CurveSetting(z.ovpv.ID));
                    }
                }
            }

        }
        private void SetYAxisLoaction()
        {
            int h = pnl_Curve.Height - 30;
            //画横向的线
            int bigDiv = (h / 50) * 10;
            h = bigDiv * 5;
            for (int i = 0; i < 5; i++)
            {
                lbl_AxisRight[i].Top = lbl_AxisLeft[i].Top = i * bigDiv - 5;
            }
            lbl_AxisRight[0].Top = lbl_AxisLeft[0].Top = 0;
            lbl_AxisRight[5].Top = lbl_AxisLeft[5].Top = h - 8;
        }
        #endregion

        #region 界面切换
        private void ShowZoneSelections(Button btn)
        {
            try
            {
                int[] v = (int[])btn.Tag;
                int groupid = v[0]; int cols = v[1];
                int w = (pnl_DayInfo.Width - 5 * cols - 5) / cols;
                pnl_DayInfo.Controls.Clear();
                ZoneGroupChk.Clear();
                ZoneGroupLbl.Clear();
                int totalzones = 0;
                //for (int i = 0; i < QueryForms.fmquery.netline.zone.Count; i++)
                foreach (var z in QueryForms.fmquery.netline.zone.Values)
                {
                    if (z.GroupID == groupid && z.isShowCurve)
                    {
                        Panel pnl = new Panel()
                        {
                            Size = new Size(w, SelectPanelHeight),
                            Location = new Point(5 + (w + 5) * (totalzones % cols), 5 + (SelectPanelHeight + 5) * (totalzones / cols)),
                            BorderStyle = BorderStyle.FixedSingle,
                            BackColor = Color.LightYellow
                        };
                        CheckBox chk = new CheckBox()
                        {
                            Text = z.ZoneName,
                            AutoSize = true,
                            Location = new Point(3, 1),
                            Checked = GetZoneCurveSelection(z.ID),
                            Tag = z,
                        };
                        chk.CheckedChanged += EquipChk_CheckedChanged;
                        pnl.MouseDown += ZonePanel_MouseDown;
                        pnl.DoubleClick += ZonePanel_DoubleClick;
                        pnl.Controls.Add(chk);
                        ZoneGroupChk.Add(chk, new List<CheckBox>());
                        ZoneGroupLbl.Add(chk, new List<Label>());
                        if (z.pv != null)
                        {
                            ZoneGroupChk[chk].Add(CreateCheckBox("pv", new Size(w / 3 - SelectPanelHeight / 2, SelectPanelHeight / 2), new Point(SelectPanelHeight / 2, SelectPanelHeight / 2), z.pv.ID, LineSetting[z.pv.ID].isshow));
                            pnl.Controls.Add(ZoneGroupChk[chk].Last());
                            ZoneGroupLbl[chk].Add(CreateLabel(new Point(1, SelectPanelHeight / 2 + 1), LineSetting[z.pv.ID].CurveColor, z.pv.ID));
                            pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                        }
                        if (z.sv != null)
                        {
                            ZoneGroupChk[chk].Add(CreateCheckBox("sv", new Size(w / 3 - SelectPanelHeight / 2, SelectPanelHeight / 2), new Point(w / 3 + SelectPanelHeight / 2, SelectPanelHeight / 2), z.sv.ID, LineSetting[z.sv.ID].isshow));
                            pnl.Controls.Add(ZoneGroupChk[chk].Last());
                            ZoneGroupLbl[chk].Add(CreateLabel(new Point(w / 3 + 1, SelectPanelHeight / 2 + 1), LineSetting[z.sv.ID].CurveColor, z.sv.ID));
                            pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                        }
                        if (z.ovpv != null)
                        {
                            ZoneGroupChk[chk].Add(CreateCheckBox("opv", new Size(w / 3 - SelectPanelHeight / 2, SelectPanelHeight / 2), new Point(2 * w / 3 + SelectPanelHeight / 2, SelectPanelHeight / 2), z.ovpv.ID, LineSetting[z.ovpv.ID].isshow));
                            pnl.Controls.Add(ZoneGroupChk[chk].Last());
                            ZoneGroupLbl[chk].Add(CreateLabel(new Point(2 * w / 3 + 1, SelectPanelHeight / 2 + 1), LineSetting[z.ovpv.ID].CurveColor, z.ovpv.ID));
                            pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                        }
                        pnl.Tag = chk;
                        pnl_DayInfo.Controls.Add(pnl);
                        totalzones++;
                    }
                }
                //设置坐标轴
                SetAxisText(groupid, true);
                SetAxisText(groupid, false);
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void Btn_Click(object sender, EventArgs e)
        {
            selectedGroupButton = sender as Button;
            ShowZoneSelections(selectedGroupButton);
            ReDrawCurves();
        }
        private void EquipChk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            Zone z = chk.Tag as Zone;
            SetZoneCurveSelection(z.ID, chk.Checked);
            ReDrawCurves();
        }
        private CheckBox CreateCheckBox(string txt, Size sz, Point pt, object tag, bool value)
        {
            CheckBox chk = new CheckBox()
            {
                Text = txt,
                Size = sz,
                Location = pt,
                Checked = value,
                Tag = tag
            };
            chk.CheckedChanged += ItemChk_CheckedChanged;
            return chk;
        }
        private void ItemChk_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            int.TryParse(chk.Tag.ToString(), out int itemid);
            if (itemid != 0)
            {
                LineSetting[itemid].isshow = chk.Checked;
                LineSetting[itemid].SaveCurveSetting();
                ReDrawCurves();
            }
        }
        private Label CreateLabel(Point pt, Color bgColor, object tag)
        {
            Label lbl = new Label()
            {
                Size = new Size(16, 16),
                Location = pt,
                Tag = tag,
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = bgColor
            };
            lbl.Click += ColorLbl_Click;
            return lbl;
        }
        private bool GetZoneCurveSelection(int zoneid)
        {
            bool isshow = true;
            if (int.TryParse(inifile.ReadValue("Zone" + zoneid, "isshow"), out int c))
                isshow = c == 1 ? true : false;
            return isshow;
        }
        private void SetZoneCurveSelection(int zoneid, bool value)
        {
            inifile.Write("Zone" + zoneid, "isshow", value ? "1" : "0");
        }
        #endregion

        #region 绘图函数
        private void ReDrawCurves()
        {
            for (int i = 0; i < DataOfDay.Count; i++)
            {
                DataOfDay[i].CurvePic.Width = (int)(2880 * xScale);
                DataOfDay[i].CurvePic.Image = DataOfDay[i].GetCurve(DataOfDay[i].CurvePic.Size, GetZoneIDs(), LineSetting);
            }
            ReOrderCurves();
        }
        private void ReOrderCurves()
        {
            int totalwidth = 0;
            for (int i = 0; i < DataOfDay.Count; i++)
            {
                DataOfDay[i].CurvePic.Location = new Point(i * DataOfDay[i].CurvePic.Width, 0);
                totalwidth += DataOfDay[i].CurvePic.Width;
            }
            if (totalwidth > (pnl_Curve.Width - pic_AxisL.Width - pic_AxisR.Width))
            {
                hScroll.Enabled = true;
                hScroll.Minimum = 0;
                hScroll.Maximum = (totalwidth - pnl_Curve.Width + pic_AxisL.Width + pic_AxisR.Width) / 15; //这里的9应该是左右的width=（60*2）/ 15 + 1 = 8 + 1=9
            }
            else
            {
                hScroll.Enabled = false;
            }
        }
        private List<int> GetZoneIDs()
        {
            List<int> ids = new List<int>();
            foreach (CheckBox chk in ZoneGroupChk.Keys)
            {
                if (chk.Checked)
                {
                    foreach (CheckBox itemchk in ZoneGroupChk[chk])
                    {
                        if (itemchk.Checked)
                        {
                            if (int.TryParse(itemchk.Tag.ToString(), out int itemid))
                            {
                                ids.Add(itemid);
                            }
                        }
                    }
                }
            }
            return ids;
        }

        #endregion

        #region 界面操作
        private void SaveYAxis(int groupid, bool isLeftAxis)
        {
            Ini curvesetting = new Ini(Application.StartupPath + "\\settings\\Curve.dat");
            if (isLeftAxis)
            {
                curvesetting.Write("EquipGroup" + groupid, "lmin", Y_Axis[groupid][0].min.ToString());
                curvesetting.Write("EquipGroup" + groupid, "lmax", Y_Axis[groupid][0].max.ToString());
                curvesetting.Write("EquipGroup" + groupid, "lunit", Y_Axis[groupid][0].unit);
            }
            else
            {
                curvesetting.Write("EquipGroup" + groupid, "rmin", Y_Axis[groupid][1].min.ToString());
                curvesetting.Write("EquipGroup" + groupid, "rmax", Y_Axis[groupid][1].max.ToString());
                curvesetting.Write("EquipGroup" + groupid, "runit", Y_Axis[groupid][1].unit);
            }
        }
        private void ZonePanel_DoubleClick(object sender, EventArgs e)//用来设置标尺范围
        {
            Panel pnl = sender as Panel;
            CheckBox chk = pnl.Tag as CheckBox;
            if (int.TryParse(ZoneGroupChk[chk][0].Tag.ToString(), out int id))
            {
                Pnl_LimitSet.Tag = chk;
                lbl_LimitSetTitle.Text = chk.Text;
                txt_LimitMax.Text = LineSetting[id].AxisMax.ToString();
                txt_LimitMin.Text = LineSetting[id].AxisMin.ToString();
                Pnl_LimitSet.Visible = true;
            }
        }
        private void ZonePanel_MouseDown(object sender, MouseEventArgs e)//用来进行左右标尺的显示
        {
            Panel pnl = sender as Panel;
            CheckBox chk = pnl.Tag as CheckBox;
            Zone z = chk.Tag as Zone;
            if (int.TryParse(ZoneGroupChk[chk][0].Tag.ToString(), out int id))
            {
                if (e.Button == MouseButtons.Left)//设置左边的
                {
                    Y_Axis[SelectedGroupID][0].min = LineSetting[id].AxisMin;
                    Y_Axis[SelectedGroupID][0].max = LineSetting[id].AxisMax;
                    Y_Axis[SelectedGroupID][0].unit = z.Unit;
                    SetAxisText(SelectedGroupID, true);
                    return;
                }
                if (e.Button == MouseButtons.Right)//设置右边的
                {
                    Y_Axis[SelectedGroupID][1].min = LineSetting[id].AxisMin;
                    Y_Axis[SelectedGroupID][1].max = LineSetting[id].AxisMax;
                    Y_Axis[SelectedGroupID][1].unit = z.Unit;
                    SetAxisText(SelectedGroupID, false);
                    return;
                }
            }
        }
        private void SetAxisText(int groupid, bool isLeftAxis)
        {
            try
            {
                float min, max;
                string unit;
                if (isLeftAxis)
                {
                    min = Y_Axis[groupid][0].min; max = Y_Axis[groupid][0].max; unit = Y_Axis[groupid][0].unit;
                }
                else
                {
                    min = Y_Axis[groupid][1].min; max = Y_Axis[groupid][1].max; unit = Y_Axis[groupid][1].unit;
                }
                Label[] lbl;
                Label lblAxisTitle;
                if (isLeftAxis) { lbl = lbl_AxisLeft; lblAxisTitle = lbl_LeftTitle; }
                else { lbl = lbl_AxisRight; lblAxisTitle = lbl_RightTitle; }
                lblAxisTitle.Text = unit;
                lbl[0].Text = Math.Round(max, 2).ToString();
                lbl[5].Text = Math.Round(min, 2).ToString();
                for (int i = 1; i < 5; i++)
                {
                    lbl[i].Text = Math.Round(min + (max - min) / 5 * (5 - i), 2).ToString();
                }
                SaveYAxis(groupid, isLeftAxis);
            }
            catch (Exception)
            {
            }

        }
        private void ColorLbl_Click(object sender, EventArgs e)
        {
            Label lbl = sender as Label;
            int.TryParse(lbl.Tag.ToString(), out int itemid);
            if (itemid != 0)
            {
                ColorDialog cd = new ColorDialog();
                cd.Color = lbl.BackColor;
                DialogResult res = cd.ShowDialog();
                if (res == DialogResult.OK)
                {
                    lbl.BackColor = cd.Color;
                    LineSetting[itemid].CurveColor = lbl.BackColor;
                    LineSetting[itemid].SaveCurveSetting();
                    ReDrawCurves();
                }
            }
        }
        private void hScroll_Scroll(object sender, ScrollEventArgs e)
        {      
            for (int i = 0; i < DataOfDay.Count; i++)
            {
                DataOfDay[i].CurvePic.Left = i * DataOfDay[i].CurvePic.Width - hScroll.Value * 15;
            }
        }
        private void ShowNextDay()
        {
            PictureBox pic = new PictureBox() { Size = new Size((int)(2880*xScale), pnl_Pics.Height) };
            pic.Click += Pic_Click;
            pic.MouseMove += Pic_MouseMove;
            pic.MouseLeave += Pic_MouseLeave;
            QueryOneDayData qd = new QueryOneDayData(nextDate) {
                CurvePic = pic
            };
            DataOfDay.Add(qd);
            reOrderPicTag();
            qd.GetOneDayData(new List<Zone>(QueryForms.fmquery.netline.zone.Values.ToArray()));
            qd.CurvePic.Image = qd.GetCurve(pic.Size, GetZoneIDs(), LineSetting);
            pnl_Pics.Controls.Add(qd.CurvePic);
            SetButtonEnable();
            nextDate = nextDate.AddDays(1);
            ReOrderCurves();
        }
        private void reOrderPicTag()
        {
            for (int i = 0; i < DataOfDay.Count; i++)
            {
                DataOfDay[i].CurvePic.Tag = i;
            }
        }
        private void Pic_MouseLeave(object sender, EventArgs e)
        {
            TimeLabel.Visible = TimeData.Visible = TimeLine.Visible = false ;
        }

        private void Pic_MouseMove(object sender, MouseEventArgs e)
        {
            PictureBox pic = sender as PictureBox;
            QueryOneDayData qd = DataOfDay[(int)pic.Tag];
            if (qd.LineTime == null) return;
            if (TimeLine.Container != pic) pic.Controls.Add(TimeLine);
            TimeLabel.Visible = TimeData.Visible = TimeLine.Visible = true;
            TimeLabel.Text =qd.LineTime[(int)(e.X / xScale)]==string.Empty?qd.QueryDate.AddMinutes(e.X/2/ xScale).ToString("yyyy-MM-dd HH:mm"):qd.LineTime[(int)(e.X / xScale)];
            StringBuilder sb = new StringBuilder();
            if (qd.isLoadDataCurrect && e.X < pic.Width  && e.X>=0)
            {
                foreach (CheckBox zonechk in ZoneGroupChk.Keys)
                {
                    sb.Append(zonechk.Text).Append(":");
                    foreach (CheckBox chk in ZoneGroupChk[zonechk])
                    {
                        int.TryParse(chk.Tag.ToString(), out int v);
                        sb.Append(chk.Text).Append(":").Append(qd.LineData[v][(int)(e.X / xScale)]).Append(" ");
                    }
                    sb.Append("\n");
                }
            }
            TimeData.Text = sb.ToString();
            TimeLine.Left = e.X - 1;
            if (e.Y < TimeData.Height)
                TimeData.Top = e.Y + 25;
            else
                TimeData.Top = e.Y - TimeData.Height;
            if (e.X +pic.Left > pnl_Pics.Width / 2)
            {
                TimeData.Left = e.X + pic.Left + pic_AxisL.Width - 2 - TimeData.Width;
                TimeLabel.Left = e.X + pic.Left + pic_AxisL.Width - 2 - TimeLabel.Width;
            }
            else
            {
                TimeLabel.Left = TimeData.Left = e.X + pic.Left + pic_AxisL.Width + 2;
            }
        }

        private void Pic_Click(object sender, EventArgs e)
        {
            //PictureBox pic = sender as PictureBox;
            //MessageBox.Show(pic.Tag.ToString());
        }
        private void ShowPreDay()
        {
            PictureBox pic = new PictureBox() { Size = new Size((int)(2880 * xScale), pnl_Pics.Height) };
            pic.Click += Pic_Click;
            pic.MouseMove += Pic_MouseMove;
            pic.MouseLeave += Pic_MouseLeave;
            QueryOneDayData qd = new QueryOneDayData(preDate)
            {
                CurvePic = pic
            };
            DataOfDay.Insert(0, qd);
            reOrderPicTag();
            qd.GetOneDayData(new List<Zone>( QueryForms.fmquery.netline.zone.Values.ToArray()) );
            qd.CurvePic.Image = qd.GetCurve(pic.Size, GetZoneIDs(), LineSetting);
            pnl_Pics.Controls.Add(qd.CurvePic);
            SetButtonEnable();
            preDate = preDate.AddDays(-1);
            ReOrderCurves();
        }
        private void SetButtonEnable() 
        {
            if (DataOfDay.Count > 10)
            {
                btn_NextDay.Enabled = btn_PreDay.Enabled = false;
                return;
            }
            else
            {
                btn_NextDay.Enabled = btn_PreDay.Enabled = true;
            }
            if (nextDate.Date == DateTime.Now.Date)
                btn_NextDay.Enabled = false;
            else
                btn_NextDay.Enabled = true;
        }
        private void ClearData()
        {
            if (DataOfDay != null && DataOfDay.Count > 0)
            {
                for (int i = 0; i < DataOfDay.Count; i++)
                {
                    DataOfDay[i].CurvePic = null;
                    DataOfDay[i] = null;
                }
                DataOfDay.Clear();
                pnl_Pics.Controls.Clear();
            }
        }
        private void btn_NextDayClick(object sender, EventArgs e)
        {
            ShowNextDay();
        }
        private void btn_PreDayClick(object sender, EventArgs e)
        {
            ShowPreDay();
        }
        private void dtp_Day_ValueChanged(object sender, EventArgs e)
        {
            isDateChanged = true;
        }
        private void dtp_Day_CloseUp(object sender, EventArgs e)
        {
            if (isLoadInterface) return;
            if (isDateChanged)
            {
                ClearData();
                nextDate = dtp_Day.Value;
                preDate = dtp_Day.Value.AddDays(-1);
                ShowNextDay();
                isDateChanged = false;
            }
        }
        private void btn_ZoomIn_Click(object sender, EventArgs e)
        {
            btn_ZoomOut.Enabled = true;
            xScale *= 2;
            if (xScale >= 8) btn_ZoomIn.Enabled = false;
            lbl_xScaleValue.Text = "× " + xScale.ToString();
            //重新绘图了
            ReDrawCurves();
        }
        private void btn_ZoomOut_Click(object sender, EventArgs e)
        {
            btn_ZoomIn.Enabled = true;
            xScale /= 2;
            if (xScale <= 0.125f) btn_ZoomOut.Enabled = false;
            lbl_xScaleValue.Text = "× " + xScale.ToString();
            //重新绘图了
            ReDrawCurves();
        }
        private void btn_LimitConfirm_Click(object sender, EventArgs e)
        {
            if (float.TryParse(txt_LimitMin.Text, out float min) && float.TryParse(txt_LimitMax.Text, out float max))
            {
                if (max == min)
                {
                    MessageBox.Show("输入的上下值不能相同。", "限值设置");
                    return;
                }
                CheckBox chk = Pnl_LimitSet.Tag as CheckBox;
                for (int i = 0; i < ZoneGroupChk[chk].Count; i++)
                {
                    CheckBox zonechk = ZoneGroupChk[chk][i] as CheckBox;
                    if (int.TryParse(zonechk.Tag.ToString(), out int id))
                    {
                        LineSetting[id].AxisMax = max > min ? max : min;
                        LineSetting[id].AxisMin = max > min ? min : max;
                        Pnl_LimitSet.Visible = false;
                        LineSetting[id].SaveCurveSetting();
                    }
                }
                ReDrawCurves();
            }
            else
            {
                MessageBox.Show("请正确的输入上下限数值。", "限值设置");
            }

        }
        private void btn_LimitCancel_Click(object sender, EventArgs e)
        {
            Pnl_LimitSet.Visible = false;
        }
        #endregion

        #region 曲线打印

        float lmin=0; float lmax = 1000;float rmin = 0; float rmax=2000;
        //输出到打印机
        private void Print_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (rdbtn_SelectDate.Checked) //打印一天的曲线
            {
                if (DataOfDay[cmb_DateList.SelectedIndex].LineData != null) 
                    PrintOneCurve(e.Graphics, DataOfDay[cmb_DateList.SelectedIndex]);
            }
            else //打印多天的曲线
            {
                if (DataOfDay[CurrentPageIndex].LineData != null)
                    PrintOneCurve(e.Graphics, DataOfDay[CurrentPageIndex]);
                CurrentPageIndex++;
                e.HasMorePages = CurrentPageIndex < DataOfDay.Count;
            }
        }
        //打印选择
        private void ShowPrintSelect()
        {
            cmb_DateList.Items.Clear();
            for (int i = 0; i < DataOfDay.Count; i++)
            {
                cmb_DateList.Items.Add(DataOfDay[i].QueryDate.ToString("yyyy-MM-dd"));
            }
            cmb_DateList.SelectedIndex = 0;
            pnl_PrintCurve.Visible = true;

        }

        private void btn_PrintCurve_Click(object sender, EventArgs e)
        {
            lmin = Convert.ToSingle(lbl_AxisLeft[5].Text);
            lmax = Convert.ToSingle(lbl_AxisLeft[0].Text);
            rmin = Convert.ToSingle(lbl_AxisRight[5].Text);
            rmax= Convert.ToSingle(lbl_AxisRight[0].Text);

            if (chk_ToPrinter.Checked)
            {
                if (DefaultPrinterName == "") return;
                if (DefaultPrinterName != cmb_Printers.Text) //保存为默认打印机
                {
                    DefaultPrinterName = cmb_Printers.Text;
                    PubPrint.SaveDefaultPrinter(DefaultPrinterName);
                }
                print.PrinterSettings.PrinterName = DefaultPrinterName;
                print.PrinterSettings.DefaultPageSettings.Landscape = true;
                pageSize = new SizeF(print.PrinterSettings.DefaultPageSettings.PrintableArea.Height, print.PrinterSettings.DefaultPageSettings.PrintableArea.Width);
                pageMargin = print.PrinterSettings.DefaultPageSettings.PrintableArea.Height * MarginScale;
                CurrentPageIndex = 0;
                print.Print();
            }
            else
            {
                //下面是打印到PDF的过程
                if (rdbtn_SelectDate.Checked) //打印一天的曲线
                    PrintCurveToPDF(new List<QueryOneDayData>() { DataOfDay[cmb_DateList.SelectedIndex] });
                else
                    PrintCurveToPDF(DataOfDay); //打印多天的曲线
            }
            pnl_PrintCurve.Visible = false;
        }

        private void PrintCurveToPDF(List<QueryOneDayData> AllDayData)
        {
            fd_PDF pdf = new fd_PDF(PdfPageOrientation.Landscape);
            pdf.Doc.PageSettings.Orientation = PdfPageOrientation.Landscape;//横向
            StringBuilder pdfFilename =new StringBuilder (Application.StartupPath).Append ("\\RecordData\\DayCurvePDF\\");
            if (!Directory.Exists(pdfFilename.ToString())) Directory.CreateDirectory(pdfFilename.ToString());
            pdfFilename.Append("DayCurve ").Append(selectedGroupButton.Text).Append(" ").Append(AllDayData[0].QueryDate.ToString("yyyy-MM-dd"));
            if (AllDayData.Count > 1) pdfFilename.Append(" to ").Append(AllDayData.Last().QueryDate.ToString("yyyy-MM-dd"));
            pdfFilename.Append(".pdf");
            for (int i = 0; i < AllDayData.Count; i++)
            {
                PrintOneCurve(pdf, AllDayData[i]);
            }
            pdf.SaveToPDF(pdfFilename.ToString());
            foreach (PdfPageBase page in pdf.Doc.Pages)
            {
                pdf.PageRemove(page);
            }
            pdf.Doc = null;
            System.Diagnostics.Process.Start(pdfFilename.ToString());
        }

        private void PrintOneCurve(Graphics g, QueryOneDayData DayData)
        {
            float h= PrintTitle(g, QueryForms.fmquery.netline.LineName + " - " + DayData.QueryDate.ToString("yyyy年MM月dd日 ") + selectedGroupButton.Text + " 曲线", 0);
            PrintLog(g);
            PrintAxis(g, h, lmax, lmin, rmax, rmin, DayData.QueryDate, DayData.QueryDate.AddDays(1));
            PrintSelectedLabel(g, _labelLoaction,_labelBlockSize, 4);
            PrintLines(g, DayData, new RectangleF(Axisleft, Axistop, Axisright- Axisleft, AxisDivHeight * 5f));
        }


        private void PrintOneCurve(fd_PDF pdf,QueryOneDayData DayData)
        {
            pdf.PagesAdd();
            PrintTitle(pdf, QueryForms.fmquery.netline.LineName + " - " + DayData.QueryDate.ToString("yyyy年MM月dd日 ") + selectedGroupButton.Text + " 曲线", 0);
            PrintLog(pdf);
            PrintAxis(pdf, 75f, lmax, lmin, rmax, rmin, DayData.QueryDate, DayData.QueryDate.AddDays(1));
            PrintSelectedLabel(pdf, 480f, 30, 4);
            PrintLines(pdf,DayData, new RectangleF(pdf.Margin + 15, pdf.Margin + 15 + 35, pdf.PageWidth - 30 - pdf.Margin * 2, 75 * 5f));
        }

        private void PrintAxis(Graphics g, float h, float LMax, float LMin, float RMax, float RMin, DateTime _startTime, DateTime _endTime)
        {
            int TimeInterval = 5;
            Pen linePen = new Pen(Color.DarkGray);
            Pen linePen2 = new Pen(Color.LightGray);
            Brush brush =new SolidBrush(Color.Black);
            Font fontAxis = new Font("微软雅黑", 8f, FontStyle.Regular);
            SizeF sf = g.MeasureString("9.999", fontAxis);
            Axisleft = pageMargin + sf.Width*1.02f;
            Axisright = pageSize.Width - pageMargin - sf.Width * 1.02f;
            Axistop = pageMargin + h;
            _labelBlockSize = new SizeF(pageSize.Width -2*pageMargin, (pageSize.Height - pageMargin * 2) / 4f);
            _labelLoaction = new PointF(pageMargin, pageSize.Height - _labelBlockSize.Height  - pageMargin);

            AxisHeight = _labelLoaction.Y- Axistop;
            AxisDivHeight = AxisHeight * 0.9f / 5f;
            //画横向的线
            string[] LAxis = new string[6];
            string[] RAxis = new string[6];
            for (int i = 1; i < 5; i++)
            {
                LAxis[i] = (LMin + (5 - i) * (LMax - LMin) / 5).ToString();
                RAxis[i] = (RMin + (5 - i) * (RMax - RMin) / 5).ToString();
            }
            LAxis[5] = LMin.ToString();
            LAxis[0] = LMax.ToString();
            RAxis[5] = RMin.ToString();
            RAxis[0] = RMax.ToString();
            SizeF v;
            for (int i = 0; i < 5; i++)
            {
                g.DrawLine(linePen, new PointF(Axisleft, Axistop + AxisDivHeight * i), new PointF(Axisright , Axistop + AxisDivHeight * i));
                 v = g.MeasureString(LAxis[i], fontAxis); 
                if (LMax != LMin) g.DrawString(LAxis[i], fontAxis, brush, new PointF(Axisleft - sf.Width *0.02f-v.Width , Axistop + AxisDivHeight * i - v.Height/2));
                if (RMax != RMin) g.DrawString(RAxis[i], fontAxis, brush, new PointF(Axisright + 0.02f*sf.Width , Axistop + AxisDivHeight * i - v.Height/2));
                for (int j = 1; j < 10; j++)
                {
                    g.DrawLine(linePen2, new PointF(Axisleft, Axistop + AxisDivHeight * i + j * (AxisDivHeight / 10)), new PointF(Axisright, Axistop + AxisDivHeight * i + j * (AxisDivHeight / 10)));
                }
            }
            g.DrawLine(linePen, new PointF(Axisleft, Axistop + AxisDivHeight * 5), new PointF(Axisright, Axistop + AxisDivHeight * 5));
             v = g.MeasureString(LAxis[5], fontAxis); 
            if (LMax != LMin) g.DrawString(LAxis[5], fontAxis, brush, new PointF(Axisleft - sf.Width * 0.02f - v.Width, Axistop + AxisDivHeight * 5 - v.Height /2));
            if (RMax != RMin) g.DrawString(RAxis[5], fontAxis, brush, new PointF(Axisright + 0.02f * sf.Width, Axistop + AxisDivHeight * 5 - v.Height /2));
            //画纵向的线
            //基本计算
            DateTime a = Convert.ToDateTime(_startTime.AddHours(1).ToString("yyyy-MM-dd HH" + ":00"));
            DateTime b = Convert.ToDateTime(_endTime.ToString("yyyy-MM-dd HH" + ":00"));
            TimeInterval = (int)b.Subtract(a).TotalMinutes / 12;
            for (int i = 0; i < TimeSep.Length; i++)
            {
                if (TimeInterval <= TimeSep[i])
                {
                    TimeInterval = TimeSep[i];
                    break;
                }
            }

            float totalMinutes = (float)_endTime.Subtract(_startTime).TotalMinutes;
            int HourLines = (int)totalMinutes / TimeInterval;
            float w = (pageSize.Width  -  Axisleft * 2) * (TimeInterval / totalMinutes);
            //开始画线
            g.DrawLine(linePen, new PointF(Axisleft, Axistop), new PointF(Axisleft, Axistop + AxisDivHeight * 5 ));
            g.DrawLine(linePen, new PointF(Axisright, Axistop), new PointF(Axisright, Axistop + AxisDivHeight * 5 ));
            string TimeString = "";
            for (int i = 1; i < HourLines; i++)
            {
                TimeString = _startTime.AddMinutes(TimeInterval*i).ToString("HH:mm");
                v = g.MeasureString(TimeString, fontAxis);
                g.DrawLine(linePen, new PointF(Axisleft + w * i, Axistop), new PointF(Axisleft + w * i, Axistop + AxisDivHeight * 5.01f ));
                g.DrawString(TimeString, fontAxis, brush, new PointF(Axisleft + w * i-v.Width /2, Axistop + AxisDivHeight * 5.02f ));
            }
            string s = _startTime.ToString("yyyy-MM-dd HH:mm");
            g.DrawString(s, fontAxis, brush, new PointF(Axisleft, Axistop + AxisDivHeight * 5.05f+sf.Height ));
            s = _endTime.ToString("yyyy-MM-dd HH:mm");
            v = g.MeasureString(s, fontAxis);
            g.DrawString(s, fontAxis, brush, new PointF(Axisright - v.Width + 0.5f*sf.Width, Axistop + AxisDivHeight * 5.05f + sf.Height));
            s = TimeInterval + "Minutes/div";
            v = g.MeasureString(s, fontAxis);
            g.DrawString(s, fontAxis, brush, new PointF(pageSize.Width / 2 - sf.Width /2f, Axistop + AxisDivHeight * 5.05f + sf.Height));
        }


        private void PrintAxis(fd_PDF pdf, float h, float LMax, float LMin, float RMax, float RMin, DateTime _startTime, DateTime _endTime)
        {
            int TimeInterval = 5;
            PdfPen linePen = pdf.PenColor(Color.DarkGray);
            PdfPen linePen2 = pdf.PenColor(Color.LightGray);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            PdfTrueTypeFont fontAxis = new PdfTrueTypeFont(new Font("微软雅黑", 8f, FontStyle.Regular), true);
            float Axisleft = pdf.Margin + 15;
            float Axisright = pdf.PageWidth - pdf.Margin - 15;
            float Axistop = pdf.Margin + 15 + 35;


            //画横向的线
            string[] LAxis = new string[6];
            string[] RAxis = new string[6];
            for (int i = 1; i < 5; i++)
            {
                LAxis[i] = (LMin + (5 - i) * (LMax - LMin) / 5).ToString();
                RAxis[i] = (RMin + (5 - i) * (RMax - RMin) / 5).ToString();
            }
            LAxis[5] = LMin.ToString();
            LAxis[0] = LMax.ToString();
            RAxis[5] = RMin.ToString();
            RAxis[0] = RMax.ToString();

            for (int i = 0; i < 5; i++)
            {
                pdf.DrawLine(linePen, new PointF(Axisleft - 2, Axistop + h * i), new PointF(Axisright + 2, Axistop + h * i));
                if (LMax != LMin) pdf.DrawString(LAxis[i], fontAxis, brush, new PointF(Axisleft - 15, Axistop + h * i - 10));
                if (RMax != RMin) pdf.DrawString(RAxis[i], fontAxis, brush, new PointF(Axisright + 2, Axistop + h * i - 10));
                for (int j = 1; j < 10; j++)
                {
                    pdf.DrawLine(linePen2, new PointF(Axisleft, Axistop + h * i + j * (h / 10)), new PointF(Axisright, Axistop + h * i + j * (h / 10)));
                }
            }
            pdf.DrawLine(linePen, new PointF(Axisleft - 2, Axistop + h * 5), new PointF(Axisright, Axistop + h * 5));
            if (LMax != LMin) pdf.DrawString(LAxis[5], fontAxis, brush, new PointF(Axisleft - 15, Axistop + h * 5 - 10));
            if (RMax != RMin) pdf.DrawString(RAxis[5], fontAxis, brush, new PointF(Axisright + 2, Axistop + h * 5 - 10));
            //画纵向的线
            //基本计算
            DateTime a = Convert.ToDateTime(_startTime.AddHours(1).ToString("yyyy-MM-dd HH" + ":00:00"));
            DateTime b = Convert.ToDateTime(_endTime.ToString("yyyy-MM-dd HH" + ":00:00"));
            TimeInterval = (int)b.Subtract(a).TotalMinutes / 9;
            for (int i = 0; i < TimeSep.Length; i++)
            {
                if (TimeInterval <= TimeSep[i])
                {
                    TimeInterval = TimeSep[i];
                    break;
                }
            }

            float totalMinutes = (float)_endTime.Subtract(_startTime).TotalMinutes;
            int HourLines = (int)totalMinutes / TimeInterval;
            float w = (pdf.PageWidth - 30 - pdf.Margin * 2) * (TimeInterval / totalMinutes);
            //开始画线
            pdf.DrawLine(linePen, new PointF(Axisleft, Axistop), new PointF(Axisleft, Axistop + h * 5 + 2));
            pdf.DrawLine(linePen, new PointF(Axisright, Axistop), new PointF(Axisright, Axistop + h * 5 + 2));
            string TimeString = "";
            for (int i = 1; i <= HourLines; i++)
            {
                // TimeString = a.AddHours(TimeInterval*i).ToString("HH:mm:ss");
                pdf.DrawLine(linePen, new PointF(Axisleft + w * i, Axistop), new PointF(Axisleft + w * i, Axistop + h * 5 + 2));
                pdf.DrawString(TimeString, fontAxis, brush, new PointF(Axisleft + w * i - 15, Axistop + h * 5 + 2));
            }
            pdf.DrawString(_startTime.ToString("yyyy-MM-dd HH:mm:ss"), fontAxis, brush, new PointF(Axisleft - 15, Axistop + h * 5));
            pdf.DrawString(_endTime.ToString("yyyy-MM-dd HH:mm:ss"), fontAxis, brush, new PointF(Axisright - 12 * 5, Axistop + h * 5));
            pdf.DrawString(TimeInterval + "Minutes/div", fontAxis, brush, new PointF(pdf.PageWidth / 2 - 35, Axistop + h * 5));
        }


        private void PrintSelectedLabel(Graphics g, PointF lblLocation,SizeF lblBlockSizeF, int cols,int rows=3)
        {
            if (cols < 1) return;
            Font ft = new Font("宋体", 12.5f, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Black);//画刷  
            Pen linePen = new Pen(Color.DarkGray, 1f);
            float lblWidth = (lblBlockSizeF.Width- (cols-1) * 5f) / cols;
            float lblHeight = (lblBlockSizeF.Height  - (rows - 1) * 5f) / rows;
            PointF pt;
            int i = 0;
            int m = 0;//标识选择曲线的索引
            float w = lblWidth / 3f;
            foreach (CheckBox item in ZoneGroupChk.Keys)
            {
                if (!item.Checked) continue;
                bool ifContainsItem = false;
                for (int j = 0; j < ZoneGroupChk[item].Count; j++)//检查内部是否有选项
                    ifContainsItem |= ZoneGroupChk[item][j].Checked;
                if (!ifContainsItem) continue;
                pt = new PointF(lblLocation.X + i % cols * (lblWidth + 5f), lblLocation.Y + i / cols * (lblHeight + 5f));
                g.DrawRectangle(linePen, pt.X, pt.Y, lblWidth, lblHeight);
                brush = new SolidBrush(Color.Black);//画刷  
                SizeF titlesize = g.MeasureString(item.Text, ft);
                g.DrawString(item.Text, ft, brush, new PointF(pt.X + 5f, pt.Y + 5f));
                m = 0;
                for (int j = 0; j < ZoneGroupChk[item].Count; j++)
                {
                    if (ZoneGroupChk[item][j].Checked)
                    {
                        brush = new SolidBrush(ZoneGroupLbl[item][j].BackColor);
                        g.FillRectangle(brush, new RectangleF(new PointF(pt.X + w * m + 5f+ titlesize.Height * 0.1f, pt.Y + titlesize.Height+5f+ titlesize.Height * 0.1f), new SizeF(titlesize.Height*0.8f , titlesize.Height*0.8f)));
                        brush = new SolidBrush(Color.Black);
                        g.DrawString(ZoneGroupChk[item][j].Text, ft, brush, new PointF(pt.X + w * m + titlesize.Height+5f, pt.Y + +titlesize.Height + 5f));
                        m++;
                    }
                }
                i++;
            }
        }


        private void PrintSelectedLabel(fd_PDF pdf, float top, float h, int cols)
        {
            if (cols < 1) return;
            Font ft = new Font("宋体", 10f, FontStyle.Regular);
            PdfTrueTypeFont pdfFont = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            PdfPen linePen = pdf.PenColor(Color.DarkGray);
            float lblWidth = (pdf.PageWidth - pdf.Margin * 2 - cols * 2 + 2) / cols;
            PointF pt;
            int i = 0;
            int m = 0;//标识选择曲线的索引
            float w = lblWidth / 3f;
            foreach (CheckBox item in ZoneGroupChk.Keys)
            {
                if (!item.Checked) continue;
                bool ifContainsItem = false;
                for (int j = 0; j < ZoneGroupChk[item].Count; j++)//检查内部是否有选项
                    ifContainsItem |= ZoneGroupChk[item][j].Checked;
                if (!ifContainsItem) continue;
                pt = new PointF(pdf.Margin + i % cols * (lblWidth + 2), top + i / cols * (h + 2));
                pdf.DrawRectangle(linePen, new RectangleF(pt, new SizeF(lblWidth, h)));
                brush = pdf.BrushColor(Color.Black);
                pdf.DrawString(item.Text, pdfFont, brush, new PointF(pt.X + 2, pt.Y + 2));
                m = 0;
                for (int j = 0; j < ZoneGroupChk[item].Count; j++)
                {
                    if (ZoneGroupChk[item][j].Checked)
                    {
                        brush = pdf.BrushColor(ZoneGroupLbl[item][j].BackColor);
                        pdf.DrawRectangle(brush, new RectangleF(new PointF(pt.X + w * m + 2, pt.Y + 17f), new SizeF(9, 9)));
                        brush = pdf.BrushColor(Color.Black);
                        pdf.DrawString(ZoneGroupChk[item][j].Text, pdfFont, brush, new PointF(pt.X + w * m + 15, pt.Y + 13f));
                        m++;
                    }
                }
                i++;
            }
        }


        private void PrintLines(Graphics g, QueryOneDayData DayData, RectangleF drawRec)
        {
            Pen linePen;
            float minuteWidth = drawRec.Width / 2880;
            foreach (CheckBox item in ZoneGroupChk.Keys)
            {
                if (!item.Checked) continue;
                for (int i = 0; i < ZoneGroupChk[item].Count; i++)
                {
                    if (!ZoneGroupChk[item][i].Checked) continue;
                    if (int.TryParse(ZoneGroupChk[item][i].Tag.ToString(), out int ItemIndex))
                    {
                        linePen = new Pen(ZoneGroupLbl[item][i].BackColor,1f);
                        //开始画线
                        float x0, y0, x1, y1;
                        x0 = drawRec.X;
                        y0 = drawRec.Y + drawRec.Height * (LineSetting[ItemIndex].AxisMax - DayData.LineData[ItemIndex][0]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
                        for (int j = 1; j < DayData.LineData[ItemIndex].Length; j++)
                        {
                            y1 = drawRec.Y + drawRec.Height * (LineSetting[ItemIndex].AxisMax - DayData.LineData[ItemIndex][j]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
                            x1 = drawRec.X + j * minuteWidth;
                            if (DayData.LineData[ItemIndex][j] * DayData.LineData[ItemIndex][j - 1] != 0)
                            {
                                g.DrawLine(linePen, new PointF(x0, y0), new PointF(x1, y1));
                            }
                            y0 = y1;
                            x0 = x1;
                        }
                    }
                }
            }
        }


        private void PrintLines(fd_PDF pdf, QueryOneDayData DayData, RectangleF drawRec)
        {
            PdfPen linePen;
            float minuteWidth = drawRec.Width / 2880;
            foreach (CheckBox item in ZoneGroupChk.Keys)
            {
                if (!item.Checked) continue;
                for (int i = 0; i < ZoneGroupChk[item].Count; i++)
                {
                    if (!ZoneGroupChk[item][i].Checked) continue;
                    if (int.TryParse(ZoneGroupChk[item][i].Tag.ToString(), out int ItemIndex))
                    {
                        linePen = new PdfPen(ZoneGroupLbl[item][i].BackColor);
                        //开始画线
                        float x0, y0, x1, y1;
                        x0 = drawRec.X;
                        y0 = drawRec.Y + drawRec.Height * (LineSetting[ItemIndex].AxisMax - DayData.LineData[ItemIndex][0]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
                        for (int j = 1; j < DayData.LineData[ItemIndex].Length; j++)
                        {
                            y1 = drawRec.Y + drawRec.Height * (LineSetting[ItemIndex].AxisMax - DayData.LineData[ItemIndex][j]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
                            x1 = drawRec.X + j * minuteWidth;
                            if (DayData.LineData[ItemIndex][j] * DayData.LineData[ItemIndex][j - 1] != 0)
                            {
                                pdf.DrawLine(linePen, new PointF(x0, y0), new PointF(x1, y1));
                            }
                            y0 = y1;
                            x0 = x1;
                        }
                    }
                }
            }
        }
        private void PrintLog(Graphics g)
        {
            //打印LOG
            string logfile = Application.StartupPath + @"\log.bmp";
            if (!File.Exists(logfile)) return;
            Image img = Image.FromFile(logfile);
            g.DrawImage(img, new RectangleF(pageSize.Width - img.Width - pageMargin, -10 + pageMargin, img.Width, img.Height));
            //pdf.DrawImage(img, new RectangleF(pdf.PageWidth - img.Width - pdf.Margin, -10 + pdf.Margin, img.Width, img.Height));
        }
        private void PrintLog(fd_PDF pdf)
        {
            //打印LOG
            string logfile = Application.StartupPath + @"\log.bmp";
            if (!File.Exists(logfile)) return;
            Image img = Image.FromFile(logfile);
            pdf.DrawImage(img, new RectangleF(pdf.PageWidth - img.Width - pdf.Margin, -10 + pdf.Margin, img.Width, img.Height));
        }

        
        private float PrintTitle(Graphics g, string title, int lcr)
        {
            Font ft = new Font("微软雅黑", 16f, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Black);//画刷  
            SizeF sf= g.MeasureString(title, ft); //  g.GetTextSize(ft, title).Width;
            float left = pageMargin;
            if (lcr == 1) left = (pageSize.Width - sf.Width) / 2;
            if (lcr == 2) left = pageSize.Width - sf.Width ;
            g.DrawString(title, ft, brush, new PointF(left, pageMargin));
            return (float)sf.Height * 1.5f;
        }
        private void PrintTitle(fd_PDF pdf, string title, int lcr)
        {
            Font ft = new Font("微软雅黑", 16f, FontStyle.Regular);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            float w = pdf.GetTextSize(ft, title).Width;
            float left = pdf.Margin;
            if (lcr == 1) left = (pdf.PageWidth - w) / 2;
            if (lcr == 2) left = pdf.PageWidth - w;
            pdf.DrawString(title, fontTitle, brush, new PointF(left, pdf.Margin));
        }
        private void btn_PrintClose_Click(object sender, EventArgs e)
        {
            pnl_PrintCurve.Visible = false;
        }
        #endregion
        private void cmb_FunctionSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cmb_FunctionSelect.SelectedIndex)
            {
                case 0:
                    return;
                case 1://显示详细数据
                    Form_QueryDataTable fmtable = new Form_QueryDataTable();
                    fmtable.ShowDialog();
                    break;
                case 2://查看报警
                    Form_QueryAlarmByDay fmalarm = new Form_QueryAlarmByDay(true, "", dtp_Day.Value.Date, dtp_Day.Value.Date.AddDays(1).AddSeconds(-1));
                    fmalarm.ShowDialog();
                    break;
                case 3://打印曲线
                    ShowPrintSelect();
                    break;
                default:
                    break;
            }
            cmb_FunctionSelect.SelectedIndex = 0;
        }

        private void chk_ToPrinter_CheckedChanged(object sender, EventArgs e)
        {
            label2.Visible =cmb_Printers.Visible =chk_ToPrinter.Checked;
        }
    }
    public class yAxis
    {
        public float min = 0;
        public float max = 1000;
        public string unit = "℃";
    }
}
